<?php
namespace Gotcha\Core\Components\DependencyFactory {
    use Gotcha\Core\Components\Debugging\Debugger;
    use Gotcha\Core\Components\DependencyFactory\Interfaces\IDependencyContainer;
    use Gotcha\Core\Components\DependencyFactory\Interfaces\IDependencyFactory;

    class DependencyContainer implements IDependencyContainer {
        protected $_IDependencyFactory;

        private $dependenciesContainer = array();

        public function __construct(
            IDependencyFactory $dependencyFactory
        ) {
            $this->_IDependencyFactory = $dependencyFactory;
        }

        public function aggregateDependencies()
        {
            $dependencyFactory = new \ReflectionClass($this->_IDependencyFactory);
            $dependenciesContainer = new \ArrayObject($this->dependenciesContainer);
            foreach($dependencyFactory->getMethods() as $method) {
                $dynamicMethodName = $method->name; // Use this method name for dynamic class method call
                $dependenciesContainer->offsetSet(substr($method->name, 6), DependencyFactory::$dynamicMethodName());
            }
            $this->dependenciesContainer = $dependenciesContainer->getArrayCopy();
        }

        /** @noinspection PhpInconsistentReturnPointsInspection */
        public function returnDependency($dependencyName)
        {
            try {
                $dependenciesContainer = new \ArrayObject($this->dependenciesContainer);
                if($dependenciesContainer->offsetExists($dependencyName)) {
                    return $dependenciesContainer->offsetGet($dependencyName);
                } else {
                    throw new \ErrorException('Cannot find dependency name in dependencies collection.');
                }
            } catch(\Exception $ex) {
                Debugger::Error('Error', $ex, true, true);
            }
        }
    }
}

